<?php

namespace dk\widget;
use dk\core\Version;

class Js extends Base {
    protected static $instance;

    /**
     * @param \weixin\core\View $plug
     */
    function bindHandle($plug) {
        $plug->regPlug('js', array($this, 'appendFiles'));
        $plug->regPlug('printJSFile', array($this, 'printJSFile'));

        $plug->regPlug('jsCode', array($this, 'code'));
        $plug->regPlug('printJSCodes', array($this, 'outCodes'));
    }

    /**
     * @return Js
     */
    public static function getInstance() {
        if (!isset(static::$instance)) {
            if($isDev = Version::isDev()){
                self::$instance = new static();
            }else{
                self::$instance = new JsCache();
            }
            self::$instance->setDev($isDev);
        }
        return static::$instance;
    }

    /**
     * @param boolean $dev
     */
    public function setDev($dev) {
        $this->dev = $dev;
    }

    protected $dev = true;
    protected $files = [];
    protected $codes = [];

    /**
     * @param $files
     * @return string
     */
    function render(){
        return $this->appendFiles($this->request);
    }

    function appendFiles($files, $cache = true){
        if(!$files){
            return null;
        }
        $this->files = array_merge($files, $this->files);
        //$this->files += $files;
        return null;
    }

    function printJSFile($files = null){
        if($files){
            $this->appendFiles($files);
        }
        if(!$this->files){
            return null;
        }
        $files = $this->files;
        return $this->jsFileHtml($files);
    }

    protected function jsFileHtml($files){
        if(!$files){
            return null;
        }
        $html = [];
        foreach ($files as $file) {
            if($this->dev && !strpos($file, '?')){
                $file .= '?r=' . rand();
            }
            $html[] =  '<script  type="text/javascript" src="' . Ui::getInstance()->render(['src' => $file]) . '"></script>';
        }
        return implode("\r\n", $html);
    }

    function code($code){
        $this->codes[] = $code;
        return null;
    }

    function outCodes(){
        $code = implode("\r\n", $this->codes);
        return <<<STR
<script>
{$code}
</script>
STR;
    }

}